package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author 崔知谦
 * @date 2025-05-22
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
    /**
     * 申请入住
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否入住
        LambdaQueryWrapper<Elder> wrapper=new LambdaQueryWrapper<>();
        //通过身份证号查询
        wrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
        //再查询状态
        wrapper.eq(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(elder)){
            throw new BaseException("老人已入住");
        }
        //更新床位
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或更新老人数据
        elder=insertOrUpdate(bed,checkInApplyDto.getCheckInElderDto());
        //保存合同信息
        insertContract(elder,checkInApplyDto);
        //保存入住信息
        CheckIn checkIn=insertCheckIn(elder,checkInApplyDto);
        //保存入住配置信息
        insertCheckInConfig(checkIn.getId(),checkInApplyDto);

    }

    private void insertCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig=new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfig.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        //属性赋值
        //老人信息赋值
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //赋值时间
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //赋值床位
        checkIn.setBedNumber(elder.getBedNumber());
        //赋值状态
        checkIn.setStatus(0);
        //赋值家属信息
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkIn);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        //初始化对象
        Contract contract = new Contract();
        //属性赋值
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        //赋值老人信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //赋值合同编号
        String number = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(number);
        //赋值开始时间和结束时间
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //赋值状态
        Integer status=startDate.isAfter(LocalDateTime.now())?0:1;
        contract.setStatus(status);
        //新增到数据库
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //先查询老人是否存在
        LambdaQueryWrapper<Elder> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        wrapper.ne(Elder::getStatus,1);
        Elder elder = elderMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(elder)){
            //不为空进行修改
            BeanUtils.copyProperties(checkInElderDto,elder);
            //更新床位与状态
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elder.setStatus(1);
            elderMapper.updateById(elder);
        }else {
            elder= new Elder();
            //为空进行插入
            BeanUtils.copyProperties(checkInElderDto,elder);
            //更新床位与状态
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elder.setStatus(1);
            elderMapper.insert(elder);
        }
        return elder;
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住申请表
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<CheckInConfig> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //获取老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //根据身份证获得年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        //设置家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //获取合同信息
        LambdaQueryWrapper<Contract> EldWarper=new LambdaQueryWrapper<>();
        EldWarper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(EldWarper);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
